#include <algorithm>
#include <sstream>

#include "./CorsMiddleware.h"
#include "../../../../tcp/code/utility/Logger.h"

void CorsMiddleware::before(HttpRequest &request)
{
    LOG_INFO("%s", "CorsMiddleware::before - Processing request");

    if (request.getMethod() == HttpRequest::Method::Options)
    {
        LOG_INFO("%s", "Processing CORS Options request"); // Options/preflight

        HttpResponse response{};
        this->handleOptionsRequest(request, response);
        throw response; // 立即结束中间件链，抛给上层响应
    }
}

void CorsMiddleware::handleOptionsRequest(const HttpRequest &request, HttpResponse &response)
{
    std::string origin = request.getHeader("Origin");

    if (!this->isOriginAllowed(origin))
    {
        LOG_ERROR("%s%s", "Origin not allowed", origin);

        response.setStatusCode(HttpResponse::StatusCode::Forbidden403);
        return;
    }

    this->addCorsHeaders(response, origin);
    response.setStatusCode(HttpResponse::StatusCode::NoContent204);

    LOG_INFO("%s", "Options request processed successfully");
}

bool CorsMiddleware::isOriginAllowed(const std::string &origin) const
{
    // 查询配置是否允许跨域
    return this->config_.allowedOrigins.empty() ||
           std::find(this->config_.allowedOrigins.begin(),
                     this->config_.allowedOrigins.end(), "*") != this->config_.allowedOrigins.end() ||
           std::find(this->config_.allowedOrigins.begin(),
                     this->config_.allowedOrigins.end(), origin) != this->config_.allowedOrigins.end();
}

void CorsMiddleware::addCorsHeaders(HttpResponse &response, const std::string &origin)
{
    try
    {
        response.addHeader("Access-Control-Allow-Origin", origin);
        if (!this->config_.allowedMethods.empty())
        {
            response.addHeader("Access-Control-Allow-Methods",
                               this->joinStr(this->config_.allowedMethods, ", ")); // 配置可能多个要拼接
        }
        if (!this->config_.allowedHeaders.empty())
        {
            response.addHeader("Access-Control-Allow-Headers",
                               this->joinStr(this->config_.allowedHeaders, ", "));
        }
        if (this->config_.allowCredentials)
        {
            response.addHeader("Access-Control-Allow-Credentials", "true");
        }
        response.addHeader("Access-Control-Max-Age",
                           std::to_string(this->config_.maxAge));

        LOG_INFO("%s", "CORS headers added successfully");
    }
    catch (const std::exception &e)
    {
        LOG_ERROR("%s%s", "Error adding CORS headers: ", e.what());
    }
}

std::string CorsMiddleware::joinStr(const std::vector<std::string> &strings, const std::string &delimiter)
{
    std::ostringstream result{};
    for (size_t i = 0; i < strings.size(); ++i)
    {
        if (i > 0)
        {
            result << delimiter;
        }
        result << strings[i];
    }
    return result.str();
}

void CorsMiddleware::after(HttpResponse &response)
{
    LOG_INFO("%s", "CorsMiddleware::after - Processing response");

    // 直接添加CORS头，简化处理逻辑
    if (!this->config_.allowedOrigins.empty())
    {
        if (std::find(this->config_.allowedOrigins.begin(), this->config_.allowedOrigins.end(), "*") !=
            this->config_.allowedOrigins.end()) // 允许所有源
        {
            addCorsHeaders(response, "*");
        }
        else // 默认允许第一个源
        {
            addCorsHeaders(response, this->config_.allowedOrigins[0]);
        }
    }
}